package com.jiutong.meipenggang.http.model.requests;


import com.jiutong.meipenggang.common.Constants;
import com.jiutong.meipenggang.http.RetrofitHandle;
import com.jiutong.meipenggang.http.SubscribeHandler;
import com.jiutong.meipenggang.http.model.services.ImageUploadService;
import com.jiutong.meipenggang.utils.SpConfig;
import com.orhanobut.logger.Logger;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import rx.Observable;
import rx.Subscriber;


/**
 * Created by Veken on 2017/12/25.
 */

public class ImageUploadRequest extends SubscribeHandler {


    /**
     * 图片上传
     */
    public void imgUpload(Subscriber subscriber, File file) {


        // 创建 RequestBody，用于封装构建RequestBody
        RequestBody requestFile =
                RequestBody.create(MediaType.parse("image/png"), file);



        MultipartBody multipartBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("type", "1")
                .addFormDataPart("userId", SpConfig.getInstance().getString(Constants.ID))
                .addFormDataPart("imgFile", getData(file.getPath()).toString()+".png", requestFile).build();

        Observable observable = RetrofitHandle.getInstance().retrofit.create(ImageUploadService.class)
                .imgUpload(multipartBody);

        toSubscribe(observable, subscriber);
    }
    /**
     *   图片到byte数组
     */
    public byte[] getData(String path) {
        byte[] data = null;
        FileInputStream input = null;
        ByteArrayOutputStream output = null;
        try {
            input = new FileInputStream(new File(path));
            output = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024*6];
            int i = 0;
            while ((i = input.read(buffer)) != -1) {
                output.write(buffer, 0, i);
            }
            data = output.toByteArray();
        } catch (FileNotFoundException ex1) {
            ex1.printStackTrace();
        } catch (IOException ex1) {
            ex1.printStackTrace();
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (output!=null){
                try {
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return data;
    }

}
